/**
 * HTTP 请求工具
 * 封装微信小程序的网络请求
 */

import { currentConfig, DEFAULT_REQUEST_CONFIG } from './config'

// 请求参数接口
interface RequestOptions {
  url: string
  method?: 'GET' | 'POST' | 'PUT' | 'DELETE'
  data?: any
  header?: Record<string, string>
  timeout?: number
}

// 响应数据接口
interface ApiResponse<T = any> {
  code: number
  message: string
  data: T
  success: boolean
}

/**
 * 通用 HTTP 请求方法
 */
export const request = <T = any>(options: RequestOptions): Promise<T> => {
  return new Promise((resolve, reject) => {
    const { url, method = 'GET', data, header = {}, timeout } = options
    
    // 构建完整URL
    const fullUrl = `${currentConfig.baseURL}${url}`
    
    // 合并请求头
    const requestHeader = {
      ...DEFAULT_REQUEST_CONFIG.header,
      ...header
    }
    
    console.log(`🌐 API请求: ${method} ${fullUrl}`)
    if (data) {
      console.log('📤 请求数据:', data)
    }
    
    wx.request({
      url: fullUrl,
      method,
      data,
      header: requestHeader,
      timeout: timeout || DEFAULT_REQUEST_CONFIG.timeout,
      success: (res) => {
        console.log(`✅ API响应:`, res.data)
        
        if (res.statusCode >= 200 && res.statusCode < 300) {
          // 请求成功
          resolve(res.data as T)
        } else {
          // HTTP 错误状态码
          const errorMsg = `HTTP ${res.statusCode}: 请求失败`
          console.error('❌ HTTP错误:', errorMsg)
          reject(new Error(errorMsg))
        }
      },
      fail: (err) => {
        console.error('❌ 网络请求失败:', err)
        
        // 处理不同类型的错误
        let errorMessage = '网络请求失败'
        if (err.errMsg) {
          if (err.errMsg.includes('timeout')) {
            errorMessage = '请求超时，请检查网络连接'
          } else if (err.errMsg.includes('fail')) {
            errorMessage = '网络连接失败，请检查网络设置'
          }
        }
        
        reject(new Error(errorMessage))
      }
    })
  })
}

/**
 * GET 请求
 */
export const get = <T = any>(url: string, params?: Record<string, any>): Promise<T> => {
  let requestUrl = url
  
  // 处理查询参数
  if (params) {
    const queryString = Object.keys(params)
      .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`)
      .join('&')
    requestUrl += `?${queryString}`
  }
  
  return request<T>({
    url: requestUrl,
    method: 'GET'
  })
}

/**
 * POST 请求
 */
export const post = <T = any>(url: string, data?: any): Promise<T> => {
  return request<T>({
    url,
    method: 'POST',
    data
  })
}

/**
 * PUT 请求
 */
export const put = <T = any>(url: string, data?: any): Promise<T> => {
  return request<T>({
    url,
    method: 'PUT',
    data
  })
}

/**
 * DELETE 请求
 */
export const del = <T = any>(url: string): Promise<T> => {
  return request<T>({
    url,
    method: 'DELETE'
  })
}

/**
 * 文件上传
 */
export const uploadFile = (url: string, filePath: string, name: string = 'file'): Promise<any> => {
  return new Promise((resolve, reject) => {
    const fullUrl = `${currentConfig.baseURL}${url}`
    
    console.log(`📤 文件上传: ${fullUrl}`)
    
    wx.uploadFile({
      url: fullUrl,
      filePath,
      name,
      header: DEFAULT_REQUEST_CONFIG.header,
      success: (res) => {
        console.log('✅ 文件上传成功:', res)
        try {
          const data = JSON.parse(res.data)
          resolve(data)
        } catch (e) {
          resolve(res.data)
        }
      },
      fail: (err) => {
        console.error('❌ 文件上传失败:', err)
        reject(new Error('文件上传失败'))
      }
    })
  })
}
